<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.loli.net/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://www.不如狐说.com').hostname,
    root: '/',
    scheme: 'Gemini',
    version: '7.7.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":false,"style":"mac"},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":true,"color":"#222","save":"auto"},
    fancybox: true,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="图及其表示方式图由两个部分组成，一是点node，二是边edge。图的表示方法由邻接表法和邻接矩阵法。当然还有其他的方式。如下所示，有一无向图，其邻接表和邻接矩阵示意图为：">
<meta property="og:type" content="article">
<meta property="og:title" content="图">
<meta property="og:url" content="http://www.不如狐说.com/archives/b1c317b.html">
<meta property="og:site_name" content="不如狐说">
<meta property="og:description" content="图及其表示方式图由两个部分组成，一是点node，二是边edge。图的表示方法由邻接表法和邻接矩阵法。当然还有其他的方式。如下所示，有一无向图，其邻接表和邻接矩阵示意图为：">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/1.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/2.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/2.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/2.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/3.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/4.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/5.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/6.png">
<meta property="og:image" content="http://www.不如狐说.com/archives/b1c317b/7.png">
<meta property="article:published_time" content="2020-04-24T15:27:31.528Z">
<meta property="article:modified_time" content="2020-04-25T03:14:43.338Z">
<meta property="article:author" content="蒙牛麦片">
<meta property="article:tag" content="DST">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://www.不如狐说.com/archives/b1c317b/1.png">

<link rel="canonical" href="http://www.不如狐说.com/archives/b1c317b.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>
<!-- jquery -->

<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

  <title>图 | 不如狐说</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不如狐说</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">大苏打</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">5</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">9</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">26</span></a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/schedule/" rel="section"><i class="fa fa-fw fa-calendar"></i>日程表</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-fw fa-heartbeat"></i>公益 404</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://www.不如狐说.com/archives/b1c317b.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="蒙牛麦片">
      <meta itemprop="description" content="不知老之将至">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不如狐说">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          图
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-24 15:27:31" itemprop="dateCreated datePublished" datetime="2020-04-24T15:27:31Z">2020-04-24</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-04-25 03:14:43" itemprop="dateModified" datetime="2020-04-25T03:14:43Z">2020-04-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/DST/" itemprop="url" rel="index">
                    <span itemprop="name">DST</span>
                  </a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>6.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>6 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="图及其表示方式"><a href="#图及其表示方式" class="headerlink" title="图及其表示方式"></a>图及其表示方式</h1><p>图由两个部分组成，一是点node，二是边edge。<br>图的表示方法由邻接表法和邻接矩阵法。当然还有其他的方式。<br>如下所示，有一无向图，其邻接表和邻接矩阵示意图为：</p>
<a id="more"></a>

<p><img src="/archives/b1c317b/1.png" alt></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Graph</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="keyword">int</span> V;</span><br><span class="line">	<span class="built_in">list</span>&lt;<span class="keyword">int</span>&gt; *adj;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	Graph(<span class="keyword">int</span> V);</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line">Graph::Graph(<span class="keyword">int</span> V)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">this</span>-&gt;V = V;</span><br><span class="line">	adj = <span class="keyword">new</span> <span class="built_in">list</span>&lt;<span class="keyword">int</span>&gt;[V];</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Graph::addEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	adj[v].push_back(w);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="图的广度优先遍历及应用"><a href="#图的广度优先遍历及应用" class="headerlink" title="图的广度优先遍历及应用"></a>图的广度优先遍历及应用</h1><p>如图所示：，从源点2开始且标记访问，与2相邻的0，3入队，并标记已经访问过。结束后，0出队，与0相邻的1，入队，由于2已经标记访问过了，不在入队。3也是如此。遍历结果2，0，3，1.<br><img src="/archives/b1c317b/2.png" alt></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">BFS</span><span class="params">(<span class="keyword">int</span> s)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 标记未被访问过的节点</span></span><br><span class="line">    <span class="keyword">bool</span> *visited = <span class="keyword">new</span> <span class="keyword">bool</span>[V];</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; V; i++)</span><br><span class="line">        visited[i] = <span class="literal">false</span>;</span><br><span class="line">	<span class="comment">// 用于BFS的队列</span></span><br><span class="line">    <span class="built_in">list</span>&lt;<span class="keyword">int</span>&gt; <span class="built_in">queue</span>;</span><br><span class="line">    <span class="comment">// 标记当前节点已被访问并且入队</span></span><br><span class="line">    visited[s] = <span class="literal">true</span>;</span><br><span class="line">    <span class="built_in">queue</span>.push_back(s);</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">list</span>&lt;<span class="keyword">int</span>&gt;::iterator i;</span><br><span class="line">    <span class="keyword">while</span>(!<span class="built_in">queue</span>.empty())&#123;<span class="comment">//开始BFS</span></span><br><span class="line">        s = <span class="built_in">queue</span>.front();</span><br><span class="line">        <span class="built_in">queue</span>.pop_front();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//遍历与s相连接的顶点，这些点存在adj[s]中</span></span><br><span class="line">        <span class="keyword">for</span> (i = adj[s].<span class="built_in">begin</span>(); i != adj[s].<span class="built_in">end</span>(); ++i)&#123;</span><br><span class="line">            <span class="keyword">if</span> (!visited[*i])&#123;</span><br><span class="line">                visited[*i] = <span class="literal">true</span>;</span><br><span class="line">                <span class="built_in">queue</span>.push_back(*i);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>应用：</p>
<ol>
<li>无权图的最小生成树和最短路径。</li>
<li>点对点网络。在点对点网络中，比如BitTorrent，广度优先搜索用于查找所有邻居节点。</li>
<li>搜索引擎中的爬虫。</li>
<li>社交网站：在社交网络中，我们可以找到某个特定的人距离为“K”的所有人。</li>
<li>GPS导航：使用广度优先搜索查找所有邻近位置。</li>
<li>网络广播:在网络中，广播机制是优先搜索所有相邻可达到节点。</li>
<li><a href="https://lambda.uta.edu/cse5317/notes/node48.html" target="_blank" rel="noopener">垃圾收集</a></li>
<li>无向图的环检测:在无向图中，BFS或DFS可以用来检测循环。在有向图中，只有深度首先可以使用搜索。</li>
<li>在Ford-Fulkerson算法中，可以使用广度先或深度先遍历，找到最大流。优先考虑BFS，时间复杂度更小。</li>
<li>判断一个图是否是可以二分，既可以使用广度优先，也可以使用深度优先遍历。</li>
<li>判断两个点之间是否存在路径。</li>
<li>从给定节点中，查找可以访问的所有节点。</li>
</ol>
<h1 id="图的深度优先遍历及应用"><a href="#图的深度优先遍历及应用" class="headerlink" title="图的深度优先遍历及应用"></a>图的深度优先遍历及应用</h1><p>从源点2开始，并标记已经访问2了，之后查找它的所有相邻顶点，重复上面操作。下面的访问顺序之一为2,0,1,3。<img src="/archives/b1c317b/2.png" alt></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">DFS</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">bool</span> visited[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	visited[v] = <span class="literal">true</span>;</span><br><span class="line">	<span class="built_in">list</span>&lt;<span class="keyword">int</span>&gt;::iterator i;</span><br><span class="line">	<span class="keyword">for</span>(i= adj[v].<span class="built_in">begin</span>(); i != adj[v].<span class="built_in">end</span>(); ++i)</span><br><span class="line">	<span class="keyword">if</span> (!visited[*i])</span><br><span class="line">		DFS(*i, visited);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>应用</p>
<ol>
<li>对于无权图，DFS可以生成最小生成树。</li>
<li>检测图中是否有循环。</li>
<li>查找给定节点uv之间是否有路径</li>
<li>拓扑排序</li>
<li>判断一个图是否可以二分</li>
<li>寻找图的强连通分量</li>
<li>迷宫问题</li>
</ol>
<h1 id="深度优先遍历的非递归实现"><a href="#深度优先遍历的非递归实现" class="headerlink" title="深度优先遍历的非递归实现"></a>深度优先遍历的非递归实现</h1><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">DFS</span><span class="params">(<span class="keyword">int</span> s, <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt; &amp;visited)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt; <span class="built_in">stack</span>;</span><br><span class="line">	<span class="built_in">stack</span>.push(s);</span><br><span class="line">	<span class="keyword">while</span> (!<span class="built_in">stack</span>.empty())</span><br><span class="line">	&#123;</span><br><span class="line">		s = <span class="built_in">stack</span>.top();</span><br><span class="line">		<span class="built_in">stack</span>.pop();</span><br><span class="line">		<span class="keyword">if</span> (!visited[s]) visited[s] = <span class="literal">true</span>;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">auto</span> i = adj[s].<span class="built_in">begin</span>();i != adj[s].<span class="built_in">end</span>();++i)</span><br><span class="line">			<span class="keyword">if</span> (!visited[*i])</span><br><span class="line">				<span class="built_in">stack</span>.push(*i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>值得注意的是，当图不是完全有向图的，需要对每个节点，重复调用DFS，这样才能遍历到每个节点。</p>
<h1 id="检测有向图中是否有环"><a href="#检测有向图中是否有环" class="headerlink" title="检测有向图中是否有环"></a>检测有向图中是否有环</h1><p><img src="/archives/b1c317b/2.png" alt></p>
<p>如在上图中，是存在0-&gt;2-&gt;0这样的环。3-&gt;3的环。当且仅当存在一条后向边才可以认为图中有环。后向边(u,v)是指节点u连接到其在深度优先搜索树中的一个祖先节点v这样的一条边。3-&gt;3这样的自循环也可以认为是一条后向边。</p>
<p>为了检测图中的后向边，对DFS递归函数的中递归栈进行跟踪。如果我们当前遍历的顶点出现在递归栈中，那么就认为存在一条后向边，图中存在循环。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">Graph::isCyclic</span><span class="params">(<span class="keyword">int</span> v, <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;&amp;visited, <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;&amp;recStack)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//recStack表示递归栈</span></span><br><span class="line">        <span class="keyword">if</span> (visited[v] == <span class="literal">false</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            visited[v] = <span class="literal">true</span>;</span><br><span class="line">            recStack[v] = <span class="literal">true</span>;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">auto</span> i=adj[v].<span class="built_in">begin</span>(); i != adj[v].<span class="built_in">end</span>();++i)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//如果节点v所连接的另一边节点i还没有被访问，</span></span><br><span class="line">                <span class="comment">//并且在节点i处存在环，那么真的存在环</span></span><br><span class="line">                <span class="keyword">if</span>(!visited[*i])</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="keyword">if</span>(isCyclic(*i, visited, recStack))</span><br><span class="line">                        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">			    <span class="comment">//如果节点i已经被访问了，且在递归栈中有i，那么有环</span></span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (recStack[*i]) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">	    &#125;</span><br><span class="line">	    recStack[v] = <span class="literal">false</span>;</span><br><span class="line">	    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>上面函数仅能够判断从节点v出发判断是否存在环，若要对整个图判断一下，需要对图中每个节点都调用一次。</p>
<h1 id="检测无向图中是否存在环"><a href="#检测无向图中是否存在环" class="headerlink" title="检测无向图中是否存在环"></a>检测无向图中是否存在环</h1><p><img src="/archives/b1c317b/3.png" alt></p>
<p>很明显，在图中是存在一个环的。对于一个正在访问的节点V，如果它的相连接的节点u已经访问过，并且不是v的父节点，那么就可以认为图中存在环。</p>
<p>比如在图中，从节点0出发，使用DFS进行遍历。访问节点1，此时节点0是1的父节点。在访问节点2，1是2的父节点，但0不是2的父节点，并且0已经被访问过了，此时就可以判定图中存在环。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">isCyclic</span><span class="params">(<span class="keyword">int</span> v, <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;&amp;visited, <span class="keyword">int</span> parent)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	visited[v] = <span class="literal">true</span>;</span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">auto</span> i = adj[v].<span class="built_in">begin</span>(); i != adj[v].<span class="built_in">end</span>(); ++i)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span> (!visited[*i])</span><br><span class="line">		&#123;<span class="comment">//这个if一定得这么写，不得两个if用&amp;&amp;连起来</span></span><br><span class="line">			<span class="keyword">if</span> (isCyclic(*i, visited, v))</span><br><span class="line">				<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (*i != parent)</span><br><span class="line">			<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>还是只能检测联通的图，如果不连通，每个位置统统调用检测一遍。</p>
<h1 id="并查集-在无向图中检测是否存在环"><a href="#并查集-在无向图中检测是否存在环" class="headerlink" title="并查集(在无向图中检测是否存在环)"></a>并查集(在无向图中检测是否存在环)</h1><p>并查集一种数据结构，它跟踪一组被划分为多个没有交集的子集中的元素。并查集有两个主要操作，<br>查找（find）:确定某个元素所在的子集，确定两个元素是否在同一个子集中。<br>联合（union）:将两个子集连接成一个子集。<br>并查集算法可用于检测无向图是否有环。此方法需要假设图不包含任何自循环，设置一个父数组parent。如</p>
<p><img src="/archives/b1c317b/4.png" alt></p>
<p>使用图的每一个顶点创建子集。parent数组的所有元素都初始化为-1(意味着每个槽就是一个子集)。如果两个顶点都在同样的子集，就可以找到一个循环。</p>
<table>
<thead>
<tr>
<th align="center">0</th>
<th align="center">1</th>
<th align="center">2</th>
</tr>
</thead>
<tbody><tr>
<td align="center">-1</td>
<td align="center">-1</td>
<td align="center">-1</td>
</tr>
</tbody></table>
<p>现在逐个处理每条边。首先是0-1边：找到顶点0和1所在的子集。由于它们属于不同的子集，故要取它们的并集。对于取并集（union），可以让节点1作为节点0的父节点，反之也可以。数组就更新为下面这样</p>
<table>
<thead>
<tr>
<th align="center">0</th>
<th align="center">1</th>
<th align="center">2</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">-1</td>
<td align="center">-1</td>
</tr>
</tbody></table>
<p>然后是1-2边：1在子集1中，2在子集2中，不在同一个子集，于是union起来，将子集1置于子集2下面。结果如下</p>
<table>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>2</td>
<td>-1</td>
</tr>
</tbody></table>
<p>最后是0-2边：0在子集2中（0在子集1中，子集1在子集2中），2也在子集2中。那么加上这条边就形成一个环。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">find</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;parent, <span class="keyword">int</span> i)</span></span></span><br><span class="line"><span class="function"></span>&#123;<span class="comment">//并查集查找，查找i所在的子集</span></span><br><span class="line">	<span class="keyword">if</span> (parent[i] == <span class="number">-1</span>)</span><br><span class="line">		<span class="keyword">return</span> i;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">find</span>(parent, parent[i]);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Union</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp;parent, <span class="keyword">int</span> x, <span class="keyword">int</span> y)</span></span></span><br><span class="line"><span class="function"></span>&#123;<span class="comment">//并查集的并</span></span><br><span class="line">	<span class="keyword">int</span> xset = <span class="built_in">find</span>(parent, x);</span><br><span class="line">	<span class="keyword">int</span> yset = <span class="built_in">find</span>(parent, y);</span><br><span class="line">	<span class="keyword">if</span> (xset != yset) &#123;</span><br><span class="line">		parent[xset] = yset;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">Graph::isCycle</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;<span class="comment">//环判定，值得一提是，这里检测的是无向图，但图的定义在添加边的时候添加单向边</span></span><br><span class="line">	<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;parent(<span class="keyword">this</span>-&gt;v, <span class="number">-1</span>);<span class="comment">//🧑数组，</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; <span class="keyword">this</span>-&gt;V; v++) </span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">auto</span> i = adj[v].<span class="built_in">begin</span>(); i != adj[v].<span class="built_in">end</span>(); ++i)</span><br><span class="line">		&#123;<span class="comment">//v和*i是一条边的两端</span></span><br><span class="line">			<span class="keyword">int</span> x = <span class="built_in">find</span>(parent, v);</span><br><span class="line">			<span class="keyword">int</span> y = <span class="built_in">find</span>(parent, *i);</span><br><span class="line">			<span class="keyword">if</span> (x == y)</span><br><span class="line">				<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">			Union(parent, x, y);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="拓扑排序"><a href="#拓扑排序" class="headerlink" title="拓扑排序"></a>拓扑排序</h1><p>拓扑排序是有向无环图所有顶点的线性排序，满足对于每一条有向边$(u,v)$，顶点$u$在$v$之前。例如，下面图的拓扑排序是“5 4 2 3 1 0”,拓扑排序次序并不唯一。</p>
<p><img src="/archives/b1c317b/5.png" alt></p>
<p>拓扑排序过程：将DFS修改一下就行了。首先需要一个栈，暂时保存结果，从某个源点S开始，对源点S相邻的点递归调用拓扑排序，结束之后再把S压入栈中。最后将栈内元素全部出战即可。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">topologicalSortUtil</span><span class="params">(<span class="keyword">int</span> v,<span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;&amp;visited,<span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt; &amp;Stack)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	visited[v] = <span class="literal">true</span>;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">auto</span> i = adj[v].<span class="built_in">begin</span>(); i != adj[v].<span class="built_in">end</span>(); ++i)</span><br><span class="line">		<span class="keyword">if</span>(!visited[*i]) topologicalSortUtil(*i, visited, Stack);</span><br><span class="line">	Stack.push(v);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">topologicalSort</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt; Stack;<span class="comment">//保存拓扑结果</span></span><br><span class="line">	<span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;visited(V, <span class="literal">false</span>);</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; V; i++)<span class="comment">//对于每个节点，若没有被访问过，都要进行拓扑排序</span></span><br><span class="line">		<span class="keyword">if</span> (visited[i] == <span class="literal">false</span>)</span><br><span class="line">			topologicalSortUtil(i, visited, Stack);</span><br><span class="line">	<span class="keyword">while</span> (Stack.empty() == <span class="literal">false</span>)</span><br><span class="line">		Stack.pop();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="有向无环图（DAG）的最长路径"><a href="#有向无环图（DAG）的最长路径" class="headerlink" title="有向无环图（DAG）的最长路径"></a>有向无环图（DAG）的最长路径</h1><p>描述：给出一个带权有向无环图(DAG)和其中的一个源点s，求出<br>s到图中所有其它顶点的最长距离。<br>众所周知，一般图最长路径问题是NPH problem。但对于DAG的最长路径问题有一个线性时间解。使用拓扑排序可以求解。</p>
<p>求解过程：首先初始化源点S到其他顶点的距离为无穷小，源点S到S的距离为0。之后对整个图DAG进行拓扑排序。按照拓扑排序后的节点顺序，更新到源点距离就行了。</p>
<p>如图：<img src="/archives/b1c317b/6.png" alt><br><img src="/archives/b1c317b/7.png" alt><br>对图a进行拓扑排序结果为$r,s,t,x,y,z$。如图b所示，并标出图中所有的边。<br>1.如图c所示，更新r到其他点的距离。<br>2.如图d所示，更新s到其他点的距离。<br>3.如图e所示，更新t到其他点的距离。<br>4.如图f所示，更新x到其他点的距离。<br>5.如图g所示，更新y到其他点的距离。<br>6.如图h所示，更新z到其他点的距离。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">longestPath</span><span class="params">(<span class="keyword">int</span> s)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt; Stack;<span class="comment">//保存拓扑排序的结果</span></span><br><span class="line">	<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;dist(<span class="keyword">this</span>-&gt;V);<span class="comment">//距离数组</span></span><br><span class="line">	<span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;visited(<span class="keyword">this</span>-&gt;V, <span class="literal">false</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//对每个位置进行拓扑排序，得到结果</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; V; i++)</span><br><span class="line">		<span class="keyword">if</span> (visited[i] == <span class="literal">false</span>)</span><br><span class="line">			topologicalSortUtil(i, visited, Stack);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//初始化所有距离为负无穷，源点距离为0</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; V; i++)</span><br><span class="line">		dist[i] = INT_MIN;</span><br><span class="line">	dist[s] = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//不断出栈，并且更新出栈元素，到其相邻的边的最长长度</span></span><br><span class="line">	<span class="keyword">while</span> (Stack.empty() == <span class="literal">false</span>) &#123;</span><br><span class="line">		<span class="keyword">int</span> u = Stack.top();</span><br><span class="line">		Stack.pop();</span><br><span class="line">		<span class="built_in">list</span>&lt;AdjListNode&gt;::iterator i;</span><br><span class="line">		<span class="keyword">if</span> (dist[u] != INT_MAX) &#123;</span><br><span class="line">			<span class="keyword">for</span> (i = adj[u].<span class="built_in">begin</span>(); i != adj[u].<span class="built_in">end</span>(); ++i)</span><br><span class="line">				<span class="keyword">if</span> (dist[i-&gt;getV()] &lt; dist[u] + i-&gt;getWeight())</span><br><span class="line">					dist[i-&gt;getV()] = dist[u] + i-&gt;getWeight();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//打印最后结果</span></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; V; i++)</span><br><span class="line">		<span class="keyword">if</span> (dist[i] == INT_MIN)</span><br><span class="line">			<span class="built_in">cout</span> &lt;&lt; <span class="string">"INF "</span>;</span><br><span class="line">		<span class="keyword">else</span> <span class="built_in">cout</span> &lt;&lt; dist[i] &lt;&lt; <span class="string">" "</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="判断图是否可以二分"><a href="#判断图是否可以二分" class="headerlink" title="判断图是否可以二分"></a>判断图是否可以二分</h1><p>若有无向图$G=(V,E)$，其顶点V可分割为两个互不相交的子集$(A,B)$，并且图中的每条边$(i,j)$所关联的两个顶点$i$和$j$分别属于这两个不同的顶点集$(V_A,U_B)$，则称图是一个<a href="[https://baike.baidu.com/item/%E4%BA%8C%E5%88%86%E5%9B%BE](https://baike.baidu.com/item/二分图)">二分图</a>。</p>
<p>如果一个图是二分图，那么可以使用两种颜色将节点划分到两个集合中（每个集合中节点的颜色一样）。</p>
<p>胃酸法：开始对任意一未染色的顶点染色，之后判断其相邻的顶点中，若未染色则将其染上和相邻顶点不同的颜色， 若已经染色且颜色和相邻顶点的颜色相同则说明不是二分图，若颜色不同则继续判断，bfs和dfs可以搞定！</p>

    </div>

    
    
    
      
  <div class="popular-posts-header">推荐文章</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\archives\fab451a5.html" rel="bookmark">堆</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\archives\63b7a160.html" rel="bookmark">动态🐢❀</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\archives\376d0826.html" rel="bookmark">回溯算法</a></div>
    </li>
  </ul>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/DST/" rel="tag"># DST</a>
          </div>

        
  <div class="post-widgets">
    <div class="wp_rating">
      <div id="wpac-rating"></div>
    </div>
  </div>


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/archives/63b7a160.html" rel="prev" title="动态🐢❀">
      <i class="fa fa-chevron-left"></i> 动态🐢❀
    </a></div>
      <div class="post-nav-item">
    <a href="/archives/e0c67a5d.html" rel="next" title="今日🤦‍">
      今日🤦‍ <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#图及其表示方式"><span class="nav-number">1.</span> <span class="nav-text">图及其表示方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#图的广度优先遍历及应用"><span class="nav-number">2.</span> <span class="nav-text">图的广度优先遍历及应用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#图的深度优先遍历及应用"><span class="nav-number">3.</span> <span class="nav-text">图的深度优先遍历及应用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#深度优先遍历的非递归实现"><span class="nav-number">4.</span> <span class="nav-text">深度优先遍历的非递归实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#检测有向图中是否有环"><span class="nav-number">5.</span> <span class="nav-text">检测有向图中是否有环</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#检测无向图中是否存在环"><span class="nav-number">6.</span> <span class="nav-text">检测无向图中是否存在环</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#并查集-在无向图中检测是否存在环"><span class="nav-number">7.</span> <span class="nav-text">并查集(在无向图中检测是否存在环)</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#拓扑排序"><span class="nav-number">8.</span> <span class="nav-text">拓扑排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#有向无环图（DAG）的最长路径"><span class="nav-number">9.</span> <span class="nav-text">有向无环图（DAG）的最长路径</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#判断图是否可以二分"><span class="nav-number">10.</span> <span class="nav-text">判断图是否可以二分</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="蒙牛麦片"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">蒙牛麦片</p>
  <div class="site-description" itemprop="description">不知老之将至</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">26</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="/781851839@qq.com.com" title="E-Mail → 781851839@qq.com.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>




<div style="">
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<script>
(function(){

   var digit=
    [
        [
            [0,0,1,1,1,0,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,0,1,1,0],
            [0,0,1,1,1,0,0]
        ],//0
        [
            [0,0,0,1,1,0,0],
            [0,1,1,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [1,1,1,1,1,1,1]
        ],//1
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,1,1],
            [1,1,1,1,1,1,1]
        ],//2
        [
            [1,1,1,1,1,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//3
        [
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,0],
            [0,0,1,1,1,1,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,1,1,0],
            [1,1,1,1,1,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,1]
        ],//4
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,1,1,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//5
        [
            [0,0,0,0,1,1,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//6
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0]
        ],//7
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//8
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,1,1,0,0,0,0]
        ],//9
        [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0]
        ]//:
    ];

var canvas = document.getElementById('canvas');

if(canvas.getContext){
    var cxt = canvas.getContext('2d');
    //声明canvas的宽高
    var H = 100,W = 700;
    canvas.height = H;
    canvas.width = W;
    cxt.fillStyle = '#f00';
    cxt.fillRect(10,10,50,50);

    //存储时间数据
    var data = [];
    //存储运动的小球
    var balls = [];
    //设置粒子半径
    var R = canvas.height/20-1;
    (function(){
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        //存储时间数字，由十位小时、个位小时、冒号、十位分钟、个位分钟、冒号、十位秒钟、个位秒钟这7个数字组成
        data.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
    })();

    /*生成点阵数字*/
    function renderDigit(index,num){
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    cxt.beginPath();
                    cxt.arc(14*(R+2)*index + j*2*(R+1)+(R+1),i*2*(R+1)+(R+1),R,0,2*Math.PI);
                    cxt.closePath();
                    cxt.fill();
                }
            }
        }
    }

    /*更新时钟*/
    function updateDigitTime(){
        var changeNumArray = [];
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        var NewData = [];
        NewData.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
        for(var i = data.length-1; i >=0 ; i--){
            //时间发生变化
            if(NewData[i] !== data[i]){
                //将变化的数字值和在data数组中的索引存储在changeNumArray数组中
                changeNumArray.push(i+'_'+(Number(data[i])+1)%10);
            }
        }
        //增加小球
        for(var i = 0; i< changeNumArray.length; i++){
            addBalls.apply(this,changeNumArray[i].split('_'));
        }
        data = NewData.concat();
    }

    /*更新小球状态*/
    function updateBalls(){
        for(var i = 0; i < balls.length; i++){
            balls[i].stepY += balls[i].disY;
            balls[i].x += balls[i].stepX;
            balls[i].y += balls[i].stepY;
            if(balls[i].x > W + R || balls[i].y > H + R){
                balls.splice(i,1);
                i--;
            }
        }
    }

    /*增加要运动的小球*/
    function addBalls(index,num){
        var numArray = [1,2,3];
        var colorArray =  ["#3BE","#09C","#A6C","#93C","#9C0","#690","#FB3","#F80","#F44","#C00"];
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    var ball = {
                        x:14*(R+2)*index + j*2*(R+1)+(R+1),
                        y:i*2*(R+1)+(R+1),
                        stepX:Math.floor(Math.random() * 4 -2),
                        stepY:-2*numArray[Math.floor(Math.random()*numArray.length)],
                        color:colorArray[Math.floor(Math.random()*colorArray.length)],
                        disY:1
                    };
                    balls.push(ball);
                }
            }
        }
    }

    /*渲染*/
    function render(){
        //重置画布宽度，达到清空画布的效果
        canvas.height = 100;
        //渲染时钟
        for(var i = 0; i < data.length; i++){
            renderDigit(i,data[i]);
        }
        //渲染小球
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,R,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();
        }
    }

    clearInterval(oTimer);
    var oTimer = setInterval(function(){
        //更新时钟
        updateDigitTime();
        //更新小球状态
        updateBalls();
        //渲染
        render();
    },50);
}

})();
</script>





      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 2019 – 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蒙牛麦片</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">72k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:06</span>
</div>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.0
  </div>

        
<div class="busuanzi-count">
  <script pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-pjax@0/pjax.min.js"></script>
  <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.getAttribute('pjax') !== null) {
      element.setAttribute('pjax', '');
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  



  <script pjax>
  if (CONFIG.page.isPost) {
    wpac_init = window.wpac_init || [];
    wpac_init.push({
      widget: 'Rating',
      id: ,
      el: 'wpac-rating',
      color: 'fc6423'
    });
    (function() {
      if ('WIDGETPACK_LOADED' in window) return;
      WIDGETPACK_LOADED = true;
      var mc = document.createElement('script');
      mc.type = 'text/javascript';
      mc.async = true;
      mc.src = '//embed.widgetpack.com/widget.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
    })();
  }
  </script>

  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  
      
<script type="text/x-mathjax-config">
    MathJax.Ajax.config.path['mhchem'] = '//cdnjs.cloudflare.com/ajax/libs/mathjax-mhchem/3.3.0';

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
        extensions: ['[mhchem]/mhchem.js'],
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });

  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') {
          next = next.nextSibling;
        }
        if (next && next.nodeName.toLowerCase() === 'br') {
          next.parentNode.removeChild(next);
        }
      }
    });
  });

  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      element = document.getElementById(all[i].inputID + '-Frame').parentNode;
      if (element.nodeName.toLowerCase() == 'li') {
        element = element.parentNode;
      }
      element.classList.add('has-jax');
    }
  });
</script>
<script>
  NexT.utils.getScript('//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML', () => {
    MathJax.Hub.Typeset();
  }, window.MathJax);
</script>

    

  


  <script async src="/js/cursor/fireworks.js"></script>




  <script src="/js/activate-power-mode.min.js"></script>
  <script>
    POWERMODE.colorful = true;
    POWERMODE.shake = false;
    document.body.addEventListener('input', POWERMODE);
  </script>

    </div>
</body>
</html>
